package com.ly.wxstore.service.weixin;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ly.wxstore.comm.ResultCode;
import com.ly.wxstore.entity.weixin.WeixinPublic;
import com.ly.wxstore.exception.ServerException;
import com.ly.wxstore.vo.JsapiSignResult;

/**
 * Jsapi sign Service.
 * 
 * @author Peter
 *
 */
@Component
public class JsapiSignService {

	private static Logger logger = LoggerFactory.getLogger(JsapiSignService.class);

	@Autowired
	private WeixinJsapiTicketService jsapiTicketService;
	
	@Autowired
	private WeixinPublicService weixinPublicService;

	@Autowired
	private WeixinConf conf;

	public JsapiSignResult sign(String url) throws ServerException {
		String jsapi_ticket = jsapiTicketService.getJsapiTicket();
		Map<String, String> ret = sign(jsapi_ticket, url);

		JsapiSignResult result = new JsapiSignResult();
		result.setSuccess(true);
		result.setCode(ResultCode.SUCCESS);
		result.setMessage(ResultCode.SUCCESS_MSG);

		WeixinPublic weixinPublic = weixinPublicService.getGlobleWeixinPublic();
		
		result.setAppId(weixinPublic.getAppId());
		result.setNonceStr(ret.get("nonceStr"));
		result.setSignature(ret.get("signature"));
		result.setTimestamp(ret.get("timestamp"));

		logger.info("nonceStr="+ret.get("nonceStr"));
		logger.info("timestamp="+ret.get("timestamp"));
		logger.info("signature="+ret.get("signature"));
		logger.info("url="+url);
		return result;
	}

	public static void main(String[] args) {
		// 第一步：获取access_token

		// 第二步：获取jsapi_ticket
		// 用第一步拿到的access_token 采用http
		// GET方式请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）：
		// https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
		// https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=NRyi9YnmjZU_VsTUSFNsOxp3GfY5ZexbnbZPMX0hAC7Zcdrn20_m7qFzHTcsaDf99g83W7K_uAwxuwyHtcrqJRlYps2FlBnNJQUauiznTdk&type=jsapi
		// {"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u3tgwh7S8MpcDcXHS8MO__V-YjhJbpE7gnR72fmm77V2b_t_LGHFWKI-i2V4DZRWsg","expires_in":7200}

		String jsapi_ticket = "bxLdikRXVbTPdHSM05e5u3tgwh7S8MpcDcXHS8MO__V-YjhJbpE7gnR72fmm77V2b_t_LGHFWKI-i2V4DZRWsg";

		// 注意 URL 一定要动态获取，不能 hardcode
		String url = "http://wx.wonderlink.com.cn/weixin/jsapi/test";
		Map<String, String> ret = sign(jsapi_ticket, url);
		for (Map.Entry<String, String> entry : ret.entrySet()) {
			System.out.println(entry.getKey() + ", " + entry.getValue());
		}

		/*
		 * jsapi_ticket=bxLdikRXVbTPdHSM05e5u3tgwh7S8MpcDcXHS8MO__V-
		 * YjhJbpE7gnR72fmm77V2b_t_LGHFWKI
		 * -i2V4DZRWsg&noncestr=7fbeaed5-5714-434b-
		 * 9ec7-bb11c95452c4&timestamp=1430721805&url=http://wx.wonderlink.com.cn/weixin/jsapi/test
		 * signature, 4bdb90156fd86b9553c027bac6aea7f1078860d0 jsapi_ticket,
		 * bxLdikRXVbTPdHSM05e5u3tgwh7S8MpcDcXHS8MO__V
		 * -YjhJbpE7gnR72fmm77V2b_t_LGHFWKI-i2V4DZRWsg url,
		 * http://wx.wonderlink.com.cn/weixin/jsapi/test nonceStr,
		 * 7fbeaed5-5714-434b-9ec7-bb11c95452c4 timestamp, 1430721805
		 */

	};

	public static Map<String, String> sign(String jsapi_ticket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		logger.info(string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

}
